package ar.uade.edu.fain.ad.client.web.servlet.salon.aperturaMesa;

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.uade.edu.fain.ad.client.web.servlet.salon.SalonServlet;
import ar.uade.edu.fain.ad.common.exception.MesaNoDisponibleException;
import ar.uade.edu.fain.ad.common.transfer.MesaVO;
import ar.uade.edu.fain.ad.common.transfer.MozoVO;
import ar.uade.edu.fain.ad.common.transfer.PedidoVO;

/**
 * Servlet implementation class SeleccionMesasServlet
 */
public class SeleccionMesasServlet extends SalonServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SeleccionMesasServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(
			HttpServletRequest request,
			HttpServletResponse response) 
			throws ServletException, IOException {
		final String mesasIDsParam = request.getParameter("mesasIDs");
		final String[] mesasIDs = mesasIDsParam.split(",");
		final Long mozoId = (Long) request.getSession().getAttribute("mozoId");
		final MozoVO mozoVO = new MozoVO();
		mozoVO.setId(mozoId);
		final HashSet<MesaVO> mesaVOs = new HashSet<MesaVO>();
		for (String mesaIdString : mesasIDs) {
			final MesaVO mesaVO = new MesaVO();
			mesaVO.setId(Long.valueOf(mesaIdString));
			mesaVOs.add(mesaVO);
		}
		try {
			final PedidoVO pedidoVO = 
					getSalonServiceDelegate().abrirPedido(mozoVO, mesaVOs);
			request.setAttribute("pedido", pedidoVO);
			forward(getViewBasePath() + "aperturaMesa/mesaAbierta.jsp", 
					request, response);
		} catch (MesaNoDisponibleException e) {
			request.setAttribute("mesaOcupada", e.getMesaVO());
			forward(getViewBasePath() + "aperturaMesa/mesaOcupada.jsp", 
					request, response);
		}
	}

}
